$(function () {

    var strReg = "^(http|https|ftp)\\://([a-zA-Z0-9\\.\\-]+(\\:[a-zA-Z0-9\\.&%\\$\\-]+)*@)*((25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])|localhost|([a-zA-Z0-9\\-]+\\.)*[a-zA-Z0-9\\-]+\\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{2}))(\\:[0-9]+)*(/($|[a-zA-Z0-9\\.\\,\\?\\'\\\\\\+&%\\$#\\=~_\\-]+))*$";
    var regUrl = new RegExp(strReg);

    $("#addAppBtn").click(function () {
        layer.open({
            type: 2,
            title: '新应用注册',
            maxmin: true,
            shadeClose: true, //点击遮罩关闭层
            area: ['500px', '700px'],
            content: base_url + '/app/toAdd'
        });
    });

    $("#addBtn").click(function () {

        $('#appIddiv').removeClass("has-error");
        $('#appNamediv').removeClass("has-error");
        $('#appPathdiv').removeClass("has-error");
        $('#appIdMsg').html("");
        $('#appNameMsg').html("");
        $('#appPathMsg').html("");

        var appId = $('#appId').val();
        if (null == appId || appId.length == 0) {
            $('#appIddiv').addClass("has-error");
            $('#appIdMsg').html("APP ID 不能为空！");
            return;
        }
        var appName = $('#appName').val();
        if (null == appName || appName.length == 0) {
            $('#appNamediv').addClass("has-error");
            $('#appNameMsg').html("应用名不能为空！");
            return;
        }
        var appPath = $('#appPath').val();
        if (null == appPath || appPath.length == 0) {
            $('#appPathdiv').addClass("has-error");
            $('#appPathMsg').html("应用路径不能为空！");
            return;
        }
        if (!regUrl.test(appPath)) {
            $('#appPathdiv').addClass("has-error");
            $('#appPathMsg').html("应用路径格式不正确！请输入正常访问路径！");
            return;
        }
        var ii = layer.load();
        $.ajax({
            url: base_url + "/app/add",
            type: "post",
            dataType: "json",
            data: $('#addAppForm').serialize(),
            success: function (data) {
                setTimeout(function () {
                    layer.close(ii);
                }, 500);
                if ("Success" == data.code) {
                    layer.confirm("添加成功！", {
                        icon: 6,
                        title: "系统提示",
                        btn: ["确定"]
                    }, function (index) {
                        layer.close(index);
                        var index2 = parent.layer.getFrameIndex(window.name);
                        parent.layer.close(index2);
                    });
                } else if ("AppExist" == data.code) {
                    $('#appIddiv').addClass("has-error");
                    $('#appIdMsg').html(data.msg);
                } else {
                    layer.alert("添加失败：" + data.msg, {icon: 5});
                }
            }
        });

    });

    $("#changeBtn").click(function () {
        $('#appIddiv').removeClass("has-error");
        $('#appNamediv').removeClass("has-error");
        $('#appPathdiv').removeClass("has-error");
        $('#appIdMsg').html("");
        $('#appNameMsg').html("");
        $('#appPathMsg').html("");

        var appId = $('#appId').val();
        var oldAppId = $('#oldAppId').val();
        if (null == appId || appId.length == 0) {
            $('#appIddiv').addClass("has-error");
            $('#appIdMsg').html("APP ID 不能为空！");
            return;
        }
        var appName = $('#appName').val();
        if (null == appName || appName.length == 0) {
            $('#appNamediv').addClass("has-error");
            $('#appNameMsg').html("应用名不能为空！");
            return;
        }
        var appPath = $('#appPath').val();
        if (null == appPath || appPath.length == 0) {
            $('#appPathdiv').addClass("has-error");
            $('#appPathMsg').html("应用路径不能为空！");
            return;
        }
        if (!regUrl.test(appPath)) {
            $('#appPathdiv').addClass("has-error");
            $('#appPathMsg').html("应用路径格式不正确！请输入正常访问路径！");
            return;
        }

        var ii = layer.load();
        $.ajax({
            url: base_url + "/app/change",
            type: "post",
            dataType: "json",
            data: $('#changeAppForm').serialize(),
            success: function (data) {
                setTimeout(function () {
                    layer.close(ii);
                }, 500);
                if ("Success" != data.code) {
                    layer.alert(data.msg, {icon: 5});
                    return;
                } else {
                    layer.confirm("更新成功！", {
                        icon: 6,
                        title: "系统提示",
                        btn: ["确定"]
                    }, function (index) {
                        layer.close(index);
                        var index2 = parent.layer.getFrameIndex(window.name);
                        parent.layer.close(index2);
                    });
                }
            }
        });

    });

    $("#toAddResources").click(function () {
        var appId = $('#appId').val();
        layer.open({
            type: 2,
            title: '新增资源',
            maxmin: true,
            shadeClose: true, //点击遮罩关闭层
            area: ['400px', '500px'],
            content: base_url + '/app/toAddResources?appId=' + appId
        });
    });

    $("#addRes").click(function () {
        $('#resNameDiv').removeClass("has-error");
        $('#resPathDiv').removeClass("has-error");
        $('#resNameMsg').html("");
        $('#resPathMsg').html("");

        var resName = $('#resName').val();
        var resPath = $('#resPath').val();

        if (null == resName || resName == "") {
            $('#resNameDiv').addClass("has-error");
            $('#resNameMsg').html("资源名称不能为空！");
            return;
        }
        if (null == resPath || resPath == "") {
            $('#resPathDiv').addClass("has-error");
            $('#resPathMsg').html("资源路径不能为空！");
            return;
        }

        var ii = layer.load();
        $.ajax({
            url: base_url + "/app/addRes",
            type: "post",
            dataType: "json",
            data: $('#addResForm').serialize(),
            success: function (data) {
                layer.close(ii);
                if ("Success" == data.code) {
                    layer.confirm("添加成功！", {
                        icon: 6,
                        title: "系统提示",
                        btn: ["确定"]
                    }, function (index) {
                        layer.close(index);
                        var index2 = parent.layer.getFrameIndex(window.name);
                        parent.layer.close(index2);
                    });
                } else {
                    layer.alert(data.msg, {icon: 5});
                    return;
                }

            }
        });
    });

    $("#refreshRedis").click(function () {
        var appId = $('#appId').val();
        $.ajax({
            url: base_url + "/app/refreshRedis?appId=" + appId,
            type: "get",
            async: false,//设置同步方式，非异步！
            cache: false,//严格禁止缓存！
            success: function (data) {
                if ("Success" == data.code) {
                    layer.alert("刷新成功", {icon: 6});
                } else {
                    layer.alert("刷新缓存失败", {icon: 5});
                }
            }
        });
    });

    $("#toAddRoles").click(function () {
        var appId = $('#appId').val();
        layer.open({
            type: 2,
            title: '新增角色',
            maxmin: true,
            shadeClose: true, //点击遮罩关闭层
            area: ['400px', '500px'],
            content: base_url + '/app/toAddRole?appId=' + appId
        });
    });

    $("#addRole").click(function () {
        $('#roleNameDiv').removeClass("has-error");
        $('#roleNameMsg').html("");

        var roleName = $('#roleName').val();

        if (null == roleName || roleName == "") {
            $('#roleNameDiv').addClass("has-error");
            $('#roleNameMsg').html("角色名不能为空！");
            return;
        }
        var appId = $('#appId').val();
        var ii = layer.load();
        $.ajax({
            url: base_url + "/app/checkRoleExist",
            type: "post",
            dataType: "json",
            async: false,//设置同步方式，非异步！
            cache: false,//严格禁止缓存！
            data: {"appId": appId, "roleName": roleName},
            success: function (data) {
                layer.close(ii);
                if ("Success" != data.code) {
                    $('#roleNameDiv').addClass("has-error");
                    $('#roleNameMsg').html("角色名已存在！");
                    return;
                } else {
                    var i2 = layer.load();
                    $.ajax({
                        url: base_url + "/app/addAppRole",
                        type: "post",
                        dataType: "json",
                        data: $('#addRoleForm').serialize(),
                        success: function (data) {
                            layer.close(i2);
                            if ("Success" == data.code) {
                                layer.confirm("添加成功！", {
                                    icon: 6,
                                    title: "系统提示",
                                    btn: ["确定"]
                                }, function (index) {
                                    layer.close(index);
                                    var index2 = parent.layer.getFrameIndex(window.name);
                                    parent.layer.close(index2);
                                });
                            } else {
                                layer.alert("添加失败：" + data.msg, {icon: 5});
                                return;
                            }

                        }
                    });
                }
            }
        });

    });

    $("#toAddAppUser").click(function () {
        var appId = $('#appId').val();
        layer.open({
            type: 2,
            title: '新增用户授权',
            maxmin: true,
            shadeClose: true, //点击遮罩关闭层
            area: ['1000px', '400px'],
            content: base_url + '/app/toAddAppUser?appId=' + appId
        });
    });

});

function changeApp(appId) {
    $.ajax({
        url: base_url + "/app/checkLeader?appId=" + appId,
        type: "get",
        success: function (data) {
            if ("Success" != data.code) {
                layer.alert("无权限修改，请联系项目负责人", {icon: 5});
                return;
            }
            layer.open({
                type: 2,
                title: '应用修改',
                maxmin: true,
                shadeClose: true, //点击遮罩关闭层
                area: ['500px', '700px'],
                content: base_url + '/app/toChange?appId=' + appId
            });
        }
    });
}

function deleteApp(appId, id) {
    $.ajax({
        url: base_url + "/app/checkLeader?appId=" + appId,
        type: "get",
        success: function (data) {
            if ("Success" != data.code) {
                layer.alert("无权限修改，请联系项目负责人", {icon: 5});
                return;
            }
            layer.confirm("是否删除APP", {
                icon: 3,
                title: "系统提示",
                btn: ["确定", "关闭"]
            }, function (index) {
                layer.close(index);
                $.ajax({
                    url: base_url + "/app/deleteApp?appId=" + appId,
                    type: "get",
                    success: function (data2) {
                        if ("Success" != data2.code) {
                            layer.alert("APP删除失败：" + data2.msg, {icon: 5});
                        } else {
                            layer.alert("APP删除成功！", {icon: 6});
                            $("#" + id).remove();
                        }
                    }
                });
            });
        }
    });
}

function changeStatus(appId, obj) {
    var value = $(obj).text();
    var type;
    if (value == "启用") {
        type = "Start";
    } else {
        type = "Stop";
    }
    $.ajax({
        url: base_url + "/app/checkLeader?appId=" + appId,
        type: "get",
        success: function (data) {
            if ("Success" != data.code) {
                layer.alert("无权限修改，请联系项目负责人", {icon: 5});
                return;
            }
            layer.confirm("是否" + value, {
                icon: 3,
                title: "系统提示",
                btn: ["确定", "关闭"]
            }, function (index) {
                layer.close(index);
                $.ajax({
                    url: base_url + "/app/changeStatus",
                    type: "post",
                    data: {"appId": appId, "status": type},
                    success: function (data2) {
                        if ("Success" != data2.code) {
                            layer.alert("项目 " + type + " 失败！", {icon: 5});
                        } else {
                            var td = $(obj).parents('tr').children('td');
                            if ("Start" == type) {
                                td.eq(6).text("启用");
                                $(obj).text("停用");
                                $(obj).removeClass("btn-primary");
                                $(obj).addClass("btn-danger");
                            } else {
                                td.eq(6).text("停用");
                                $(obj).text("启用");
                                $(obj).removeClass("btn-danger");
                                $(obj).addClass("btn-primary");
                            }
                        }
                    }
                });
            });
        }
    });
}

function showText(num, obj) {
    var td = $(obj).parents('tr').children('td');
    var data = td.eq(num).text();
    var str = "";
    if (data.indexOf(";") != -1) {
        var leaders = data.split(";");
        for (var i = 0; i < leaders.length; i++) {
            str += leaders[i];
            if (i != leaders.length) {
                str += " <br> ";
            }
        }
    } else {
        str = data;
    }
    layer.alert(str, {icon: 6});
}

function ckeckAppLeader() {
    var appId = $('form').find('#appId').val();
    if (null == appId || appId == "") {
        return false;
    }
    var result = false;
    $.ajax({
        url: base_url + "/app/checkLeader?appId=" + appId,
        type: "get",
        async: false,//设置同步方式，非异步！
        cache: false,//严格禁止缓存！
        success: function (data) {
            if ("Success" == data.code) {
                result = true;
            }
        }
    });
    if (!result) {
        layer.alert("无权限修改，请联系项目负责人", {icon: 5});
        return false;
    }
    return true;
}

function toUpdateRole(appId, roleId) {
    $.ajax({
        url: base_url + "/app/checkLeader?appId=" + appId,
        type: "get",
        success: function (data) {
            if ("Success" != data.code) {
                layer.alert("无权限修改，请联系项目负责人", {icon: 5});
                return;
            }
            layer.open({
                type: 2,
                title: '角色修改',
                maxmin: true,
                shadeClose: true, //点击遮罩关闭层
                area: ['400px', '500px'],
                content: base_url + '/app/toUpdateRole?id=' + roleId
            });
        }
    });
}

function updateRole() {

    var i2 = layer.load();
    $.ajax({
        url: base_url + "/app/updateRole",
        type: "post",
        dataType: "json",
        data: $('#updateRoleForm').serialize(),
        success: function (data) {
            layer.close(i2);
            if ("Success" == data.code) {
                layer.confirm("更新成功！", {
                    icon: 6,
                    title: "系统提示",
                    btn: ["确定"]
                }, function (index) {
                    layer.close(index);
                    var index2 = parent.layer.getFrameIndex(window.name);
                    parent.layer.close(index2);
                });
            } else {
                layer.alert("更新失败：" + data.msg, {icon: 5});
                return;
            }

        }
    });
}

function deleteRole(id) {
    var result;
    layer.confirm("确认删除", {
        icon: 3,
        title: "系统提示",
        btn: ["确定", "关闭"]
    }, function (index) {
        layer.close(index);
        $.ajax({
            url: base_url + "/app/deleteRole?id=" + id,
            type: "get",
            async: false,//设置同步方式，非异步！
            cache: false,//严格禁止缓存！
            success: function (data) {
                result = data;
            }
        });
        if ("Success" == result.code) {
            layer.alert("删除成功！", {icon: 6});
            $("#" + id).remove();
        } else {
            layer.alert("删除失败：" + result.msg, {icon: 5});
        }
    });
}

function changeRoleStatus(roleId, obj) {
    var value = $(obj).text();
    layer.confirm("是否" + value, {
        icon: 3,
        title: "系统提示",
        btn: ["确定", "关闭"]
    }, function (index) {
        layer.close(index);
        var type;
        if (value == "启用") {
            type = "Start";
        } else {
            type = "Stop";
        }
        $.ajax({
            url: base_url + "/app/changeRoleStatus",
            type: "post",
            data: {"id": roleId, "status": type},
            success: function (data) {
                if ("Success" != data.code) {
                    layer.alert("项目 " + type + " 失败！", {icon: 5});
                } else {
                    var td = $(obj).parents('tr').children('td');
                    if ("Start" == type) {
                        td.eq(3).text("启用");
                        $(obj).text("停用");
                        $(obj).removeClass("btn-primary");
                        $(obj).addClass("btn-danger");
                    } else {
                        td.eq(3).text("停用");
                        $(obj).text("启用");
                        $(obj).removeClass("btn-danger");
                        $(obj).addClass("btn-primary");
                    }
                }
            }
        });
    });
}

function toUpdateRes(appId, resId) {
    $.ajax({
        url: base_url + "/app/checkLeader?appId=" + appId,
        type: "get",
        success: function (data) {
            if ("Success" != data.code) {
                layer.alert("无权限修改，请联系项目负责人", {icon: 5});
                return;
            }
            layer.open({
                type: 2,
                title: '资源修改',
                maxmin: true,
                shadeClose: true, //点击遮罩关闭层
                area: ['400px', '500px'],
                content: base_url + '/app/toUpdateResources?resId=' + resId
            });
        }
    });
}

function deleteRes(id) {
    var result;
    layer.confirm("确认删除", {
        icon: 3,
        title: "系统提示",
        btn: ["确定", "关闭"]
    }, function (index) {
        layer.close(index);
        $.ajax({
            url: base_url + "/app/deleteResources?resId=" + id,
            type: "get",
            async: false,//设置同步方式，非异步！
            cache: false,//严格禁止缓存！
            success: function (data) {
                result = data;
            }
        });
        if ("Success" == result.code) {
            layer.alert("删除成功！", {icon: 6});
            $("#" + id).remove();
        } else {
            layer.alert("删除失败：" + result.msg, {icon: 5});
        }
    });
}

function updateRes() {
    var i2 = layer.load();
    $.ajax({
        url: base_url + "/app/updateResources",
        type: "post",
        dataType: "json",
        data: $('#updateResForm').serialize(),
        success: function (data) {
            layer.close(i2);
            if (data) {
                layer.confirm("更新成功！", {
                    icon: 6,
                    title: "系统提示",
                    btn: ["确定"]
                }, function (index) {
                    layer.close(index);
                    var index2 = parent.layer.getFrameIndex(window.name);
                    parent.layer.close(index2);
                });
            } else {
                layer.alert("更新失败！", {icon: 5});
                return;
            }
        }
    });
}

function deleteAppUser(username, id) {
    var result = false;
    layer.confirm("确认删除", {
        icon: 3,
        title: "系统提示",
        btn: ["确定", "关闭"]
    }, function (index) {
        layer.close(index);
        var appId = $('#appId').val();
        $.ajax({
            url: base_url + "/app/deleteAppUser",
            type: "post",
            data: {"appId": appId, "username": username},
            async: false,//设置同步方式，非异步！
            cache: false,//严格禁止缓存！
            success: function (data) {
                if ("Success" == data.code) {
                    result = true;
                }
            }
        });
        if (result) {
            layer.alert("删除成功！", {icon: 6});
            $("#" + id).remove();
        } else {
            layer.alert("删除失败！", {icon: 5});
        }
    });
}

function addAppUser() {
    var users = $('#duallist').val();
    if (null == users || users.length == 0) {
        var index = parent.layer.getFrameIndex(window.name);
        parent.layer.close(index);
        return
    }
    var appId = $('#appId').val();
    $.ajax({
        url: base_url + "/app/addAppUser",
        type: "post",
        data: {"appId": appId, "users": users + ""},
        success: function (data) {
            if ("Success" == data.code) {
                layer.confirm("添加成功！", {
                    icon: 6,
                    title: "系统提示",
                    btn: ["确定"]
                }, function (index) {
                    layer.close(index);
                    var index2 = parent.layer.getFrameIndex(window.name);
                    parent.layer.close(index2);
                });
            } else {
                layer.alert("添加失败：" + data.msg, {icon: 5});
            }
        }
    });
}

function closePage() {
    var index = parent.layer.getFrameIndex(window.name);
    parent.layer.close(index);
}

function toAddAppUserRole(username) {
    var appId = $('#appId').val();
    layer.open({
        type: 2,
        title: '用户授权',
        maxmin: true,
        shadeClose: true, //点击遮罩关闭层
        area: ['1000px', '400px'],
        content: base_url + '/app/toAddAppUserRole?appId=' + appId + "&username=" + username
    });
}

function addAppUserRole() {
    var appId = $('#appId').val();
    var roles = $('#duallist').val();
    var username = $('#username').val();
    var leader = $('#leader').val();
    var isLeader = $('input[name="isLeader"]:checked').val();
    var ii = layer.load();
    $.ajax({
        url: base_url + "/app/addAppUserRole",
        type: "post",
        data: {"appId": appId, "username": username, "leader": leader, "isLeader": isLeader, "roles": roles + ""},
        success: function (data) {
            layer.close(ii);
            if ("Success" == data.code) {
                layer.confirm("授权成功！", {
                    icon: 6,
                    title: "系统提示",
                    btn: ["确定"]
                }, function (index) {
                    layer.close(index);
                    var index2 = parent.layer.getFrameIndex(window.name);
                    parent.layer.close(index2);
                });
            } else {
                layer.alert(data.msg, {icon: 5});
            }
        }
    });
}

function toAddResourcesRole(id) {
    var appId = $('#appId').val();
    layer.open({
        type: 2,
        title: '资源限制',
        maxmin: true,
        shadeClose: true, //点击遮罩关闭层
        area: ['1000px', '400px'],
        content: base_url + '/app/toAddResourcesRole?appId=' + appId + "&resId=" + id
    });
}

function addResourcesRole() {
    var appId = $('#appId').val();
    var roles = $('#duallist').val();
    var resId = $('#resId').val();
    var ii = layer.load();
    $.ajax({
        url: base_url + "/app/addResourcesRole",
        type: "post",
        data: {"appId": appId, "resId": resId, "roles": roles + ""},
        success: function (data) {
            layer.close(ii);
            if ("Success" == data.code) {
                layer.confirm("授权成功！", {
                    icon: 6,
                    title: "系统提示",
                    btn: ["确定"]
                }, function (index) {
                    layer.close(index);
                    var index2 = parent.layer.getFrameIndex(window.name);
                    parent.layer.close(index2);
                });
            } else {
                layer.alert(data.msg, {icon: 5});
            }
        }
    });

}